package Week6.J0523;
// dfs
public class 矩阵最长递增路径_xv {
    int n, m;
    int[] dx = {0, 0, 1, -1};
    int[] dy = {1, -1, 0 ,0};
    int[][] memo = new int[1010][1010];

    public int solve (int[][] matrix) {
        int ret = 1;
        n = matrix.length;
        m = matrix[0].length;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                memo[i][j] = -1;
            }
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                ret = Math.max(ret, dfs(matrix, i, j));
            }
        }
        return ret;
    }

    private int dfs(int[][] matrix, int i, int j) {
        int len = 1;
        if (memo[i][j] != -1) return memo[i][j];
        for (int k = 0; k < 4; k++) {
            int x = i + dx[k], y = j + dy[k];
            if (x >= 0 && x < n && y >= 0 && y < m && matrix[x][y] > matrix[i][j]) {
                len = Math.max(len, 1 + dfs(matrix, x, y));
            }
        }
        memo[i][j] = len;
        return len;
    }
}
